class Comment < ActiveRecord::Base
  #
  # Relations
  #

  belongs_to :offer, :class_name => 'Offer', :autosave => true
  belongs_to :user, :class_name => 'User'

  #
  # Validation
  #

  validates :title, :presence => true
  validates :content, :presence => true

  #
  # Methods
  #

  def initialize(params=nil)
    if params
      params[:user] = User.current
      params[:offer] = Offer.find(params[:offer])
      border_left = 2
      border_right = 3
    end
    super
  end

  def save_with_parent(parent_id)
    parent = Comment.find(parent_id)

    self.border_left = parent.border_right
    self.border_right = self.border_left + 1

    comments_updated = Comment.find(:all, :conditions => "border_right >= #{parent.border_right}")

    comments_updated.each do |comment_updated|
      comment_updated.border_right += 2
      comment_updated.save
    end

    self.save
  end

end
